package cn.hchaojie.camp.day10;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Arrays;

import org.junit.Test;

public class DemoRandomAccessFile {
	@Test
	public void test() {
		//String source = "test.txt";
		String source = "C:\\Users\\hchaojie\\Pictures\\video\\InletexEMC.exe";
		//String target = "‪C:\\Users\\hchaojie\\Pictures\\video\\copy.jpg";
		String target = "‪C:\\";
		String s2 = "C:\\";
		
		System.out.println(Arrays.toString(target.getBytes()));
		System.out.println(Arrays.toString(s2.getBytes()));

//		String target = "C:\\Users\\hchaojie\\Pictures\\video\\InletexEMC2.exe";
		
//		 System.out.println(new File(source).exists());
//		copy(source, target);
	}
	
	@Test
	public void copyRemain() {
		String source = "C:\\Users\\hchaojie\\Pictures\\video\\InletexEMC.exe";
		String target = "C:\\Users\\hchaojie\\Pictures\\video\\InletexEMC2.exe";
		
		File targetFile = new File(target);

		try (
			RandomAccessFile raf = new RandomAccessFile(source, "r");
			FileOutputStream fo = new FileOutputStream(target, true);
			) { // 以只读方式打开
			
//			long filePointer = raf.getFilePointer();	// 获取文件指针的位置
//			raf.seek(1024);		// 移动文件指针
			
			long size = targetFile.length();	// 已经复制了多少字节
			raf.seek(size);
			
			byte[] bytes = new byte[1024];
			int count = 0;
			while ((count = raf.read(bytes)) != -1) {
				fo.write(bytes, 0, count);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static void copy(String source, String target) {
		try (
			FileInputStream fi = new FileInputStream(source);
			FileOutputStream fo = new FileOutputStream(target);
		) {
			byte[] bytes = new byte[1024];
			int count = 0;
			
			// 文件大小
			File f = new File(source);
			long size = f.length();

			// 取到一个随机的位置
			long ran = (long) (Math.random() * size);
			
			long sum = 0;
			while ((count = fi.read(bytes)) != -1) {
				// 复制到随机的位置时，中断
				sum += count;
				if (sum >= ran) break;
				
				fo.write(bytes, 0, count);
			}
			
			System.out.println("文件大小" +  size);;
			System.out.println("复制停止：" + ran);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
